package org.four.web.controller;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.four.common.model.*;
import org.four.common.utils.Md5Util;
import org.four.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;

@Controller
@RequestMapping("web")
public class WebController {

    @Autowired
    private UserService userService;

    @Autowired
    private MongoTemplate mongoTemplate;

    //用户账号登陆
    @RequestMapping("login")
    @ResponseBody
    public Map login(HttpSession session, UserBean userBean){
        //总返回
        HashMap<String, Object> result = new HashMap<>();
        //获取验证码
        /*Object attribute = session.getAttribute("imgcode");
        if(attribute==null) {
            result.put("code", 1);
            result.put("msg", "验证码错误");
            return result;
        }*/
        //判断session中的验证码和输入的验证码是否一致
        /*int imgCode = Integer.parseInt(attribute.toString());
        if(imgCode!=code) {
            result.put("code", 1);
            result.put("msg", "验证码错误");
            return result;
        }*/
        //判断账户
        UserBean userInfo = userService.testAccount(userBean.getAccount());
        if (userInfo == null) {
            result.put("code", 2);
            result.put("msg", "账号错误");
            return result;
        }
        //判断密码
        String md532 = Md5Util.getMd532(userBean.getPassword());
        if (!userInfo.getPassword().equals(md532)) {
            result.put("code",3);
            result.put("msg","账号或者密码错误");
            return result;
        }
        result.put("code", 0);
        result.put("msg", "登陆成功");
        session.setAttribute(session.getId(),userInfo);
        session.setAttribute("account",userInfo.getAccount());
        return result;
    }
    //Es
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    //索引  这个就用一次 就是讲数据库的 数据 存进es索引库
    @RequestMapping("cratetIndex")
    @ResponseBody
    public Boolean cratetIndex (){
        //将查出来的数据存入elastic
        boolean exists = elasticsearchTemplate.indexExists(ZhaoPinBean.class);
        if (!exists) {
            elasticsearchTemplate.createIndex(ZhaoPinBean.class);
        }
        List<ZhaoPinBean> zhaoPins = userService.findZhaoPin();
        ArrayList<IndexQuery> indexQueries = new ArrayList<>();
        for (ZhaoPinBean zhaoPin : zhaoPins) {
            IndexQuery indexQuery = new IndexQueryBuilder()
                    .withId(zhaoPin.getId().toString())
                    .withObject(zhaoPin)
                    .build();
            indexQueries.add(indexQuery);
        }
        elasticsearchTemplate.bulkIndex(indexQueries);
        return true;
    }





    //招聘岗位 高亮
    @RequestMapping("findZhaoPinList")
    @ResponseBody
    public List findZhaoPinList(Integer page, Integer rows , String title) {
        //注意开始是从0开始，有点类似sql中的方法limit 的查询
        PageRequest pageable = PageRequest.of(page - 1, rows);
        //高亮
        HighlightBuilder.Field highlightBuilder = new HighlightBuilder.Field("title").preTags("<em style='color:red'>").postTags("</em>");
        //搜索条件
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        if (!StringUtils.isEmpty(title)){
            boolQueryBuilder.must(matchQuery("title",title));
        }
        NativeSearchQuery searchQueryBuilder = nativeSearchQueryBuilder.withQuery(boolQueryBuilder)//这个queryBuilder 是用ctrl 点击 withQuery 进去的 参数
                .withHighlightFields(highlightBuilder)
                .withPageable(pageable)
                .build();
        // long count = elasticsearchTemplate.count(searchQueryBuilder,GoodsBean.class);
        // List<GoodsBean> goodsBeans = elasticsearchTemplate.queryForList(searchQueryBuilder, GoodsBean.class);
        AggregatedPage<ZhaoPinBean> zhaoPinBeans = elasticsearchTemplate.queryForPage(searchQueryBuilder, ZhaoPinBean.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                SearchHits hits = searchResponse.getHits();
                List<T> chunk = new ArrayList<>();

                for (SearchHit hit : hits) {
                    Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                    Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                    chunk.add((T)createBean(sourceAsMap,highlightFields));
                }
                AggregatedPage<T> result=new AggregatedPageImpl<T>(chunk,pageable,searchResponse.getHits().getTotalHits());
                return result;
            }
        });
        //获取总共多少条数据
        long totalElements = zhaoPinBeans.getTotalElements();
        //获取返回内容
        List<ZhaoPinBean> content = zhaoPinBeans.getContent();
        LayuiPage layuiPage = new LayuiPage();
        layuiPage.setCode(0);
        layuiPage.setCount((int) totalElements);
        layuiPage.setMsg("查询成功");
        layuiPage.setData(content);
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("total",totalElements);
        objectObjectHashMap.put("rows",content);
        return content;
    }

    //上面对应的
    private ZhaoPinBean createBean(Map<String, Object> sourceAsMap,Map<String, HighlightField> highlightFields){
        HighlightField productName = highlightFields.get("title");
        String title = "";
        if (productName != null){
            Text[] fragments = productName.getFragments();
            for (Text fragment : fragments) {
                title += fragment.toString();
            }
        }
        sourceAsMap.put("title",highlightFields.size() > 0 ? title: sourceAsMap.get("title"));
        String jsonString = JSON.toJSONString(sourceAsMap);
        ZhaoPinBean zhaoPinBean = JSON.parseObject(jsonString, ZhaoPinBean.class);
        return zhaoPinBean;
    }

    //查询树
    @RequestMapping("findNav")
    @ResponseBody
    public List<NavBean> findNav(){
        return userService.findTree();
    }

    //登陆
    /*@RequestMapping("login")
    @ResponseBody
    public Map login(UserBean userBean){
        return userService.login(userBean);
    }*/

    //注册
    @RequestMapping("reg")
    @ResponseBody
    public Map reg(UserBean userBean){
        HashMap<String, Object> result = new HashMap<>();
        String account = userBean.getAccount();
        UserBean user=userService.testAccount(account);
        if(user!=null){
            result.put("code",1);
            result.put("msg","该账号太受欢迎了");
            return result;
        }
        String md532 = Md5Util.getMd532(userBean.getPassword());
        userBean.setPassword(md532);
        userService.saveUser(userBean);
        result.put("code",0);
        result.put("msg","注册成功");
        return result;
    }

    //注销
    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute(session.getId());
        return "twowjs/login";
    }

    //新增简历
    @RequestMapping("addProduct")
    @ResponseBody
    public String addProduct(ProductBean productBean,HttpSession session){
        if(productBean.getId()!=null){
            try {
                userService.upda(productBean);
                return "1";
            }
            catch (Exception e) {
                e.printStackTrace();
                return "0";
            }
        }else {
            try {
                UserBean userBean = (UserBean) session.getAttribute(session.getId());
                productBean.setUserid(userBean.getId());
                userService.addUser(productBean);
                return "1";
            } catch (Exception e) {
                e.printStackTrace();
                return "0";
            }
        }
    }

    //查询简历
    @RequestMapping("queryProduct")
    @ResponseBody
    public LayuiPage queryProduct(int limit , int page,HttpSession session){
        UserBean userBean = (UserBean) session.getAttribute(session.getId());
        return userService.queryProduct(limit,page,userBean.getId());
    }

    //我的投递
    @RequestMapping("toudi")
    @ResponseBody
    public LayuiPage toudi(int limit , int page,HttpSession session){
        UserBean userBean = (UserBean) session.getAttribute(session.getId());
        return userService.toudi(limit,page,userBean.getId());
    }

    //简历回显
    @RequestMapping("findProductInfo")
    @ResponseBody
    public ProductBean findProductInfo(Integer id){
        ProductBean productInfo = userService.findProductInfo(id);
        return productInfo;
    }

    //订阅回显
    @RequestMapping("findyue")
    @ResponseBody
    public ZhiweiBean findyue(Integer id){
        ZhiweiBean productInfo = userService.findyue(id);
        return productInfo;
    }

    //新增职位和修改职位
    @RequestMapping("adddingyue")
    @ResponseBody
    public String adddingyue(ZhiweiBean zhiweiBean){
        if(zhiweiBean.getId()!=null){
            try {
                userService.updacjq(zhiweiBean);
                return "1";
            }
            catch (Exception e) {
                e.printStackTrace();
                return "0";
            }
        }else {
            try {
                userService.addProductcjq(zhiweiBean);
                return "1";
            } catch (Exception e) {
                e.printStackTrace();
                return "0";
            }
        }
    }

    //查询商品列表
    @RequestMapping("queryProductcjq")
    @ResponseBody
    public LayuiPage queryProductcjq(HttpSession session){
        UserBean userBean = (UserBean) session.getAttribute(session.getId());
        LayuiPage layuiPage = userService.queryProductcjq(userBean.getId());
        return layuiPage;
    }

    //收藏查询列表
    @RequestMapping("queryzhiwei")
    @ResponseBody
    public LayuiPage queryzhiwei(int limit, int page){
        LayuiPage layuiPage = userService.queryzhiwei(limit, page);
        return layuiPage;
    }

    //订阅查询列表
    /*@RequestMapping("querydingyue")
    @ResponseBody
    public LayuiPage querydingyue(int limit, int page,ZhiweiBean zhiweiBean){
        LayuiPage layuiPage = userService.querydingyue(limit, page,zhiweiBean);
        return layuiPage;
    }*/

    @RequestMapping("querydingyue")
    @ResponseBody
    public LayuiPage querydingyue(int limit, int page,ZhiweiBean zhiweiBean, HttpServletRequest request){
        LayuiPage layuiPage = userService.querydingyue(limit, page,zhiweiBean);
        return layuiPage;
    }

    //删除收藏管理
    @RequestMapping("delcjq")
    @ResponseBody
    public String delcjq(Integer[] id){
        try{
            userService.delcjq(id);
            return "1";
        }catch (Exception e){
            e.printStackTrace();
            return "0";
        }
    }

    //删除订阅
    @RequestMapping("del2")
    @ResponseBody
    public String del2(Integer[] id){
        try{
            userService.del2(id);
            return "1";
        }catch (Exception e){
            e.printStackTrace();
            return "0";
        }
    }

    //账号设置查询
    @RequestMapping("haolist")
    @ResponseBody
    public LayuiPage haolist(int limit , int page){
        return userService.haolist(limit,page);
    }

    //账号设置
    @RequestMapping("zhanggai")
    @ResponseBody
    public void zhanggai(UserBean userBean) {
        userService.zhanggai(userBean);
    }

    //测试
    @RequestMapping("queryList")
    @ResponseBody
    public LayuiPage queryList(Integer page, Integer limit, Integer sort, ZhaoPinBean zhaoPinBean){
        return userService.queryList(page,limit,sort,zhaoPinBean);
    }

    //查询类型
    @RequestMapping("queryType")
    @ResponseBody
    public List<ComUserBean> queryType(){
        return userService.queryType();
    }

    //投递简历
    @RequestMapping("addli")
    public void addli(@RequestBody ToudiBean toudiBean){
        userService.addli(toudiBean);
    }

    /**
     * 获取登录账号
     * @param session
     * @return
     */
    @RequestMapping("checkLogin")
    @ResponseBody
    public Map checkLogin(HttpSession session){
        HashMap<String, Object> result = new HashMap<>();
        UserBean userBean = (UserBean) session.getAttribute(session.getId());
        System.out.println(session.getId());
        if (userBean==null){
            result.put("code",1);
            result.put("msg","未登陆");
            return result;
        }
        result.put("code",2);
        result.put("msg","已登陆");
        result.put("truename",userBean.getAccount());
        return result;
    }

    //修改收藏状态
    @RequestMapping("productState")
    @ResponseBody
    public Boolean productState(Integer id){
        try {
            userService.productState(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 跳转
     * */
    @RequestMapping("jiekou")
    @ResponseBody
    public List<ZhaoPinBean> findProductListImg(){
        return userService.findProductListImg();
    }

    /**
     * 根据id查询商品详情
     * */
    @RequestMapping("queryProductById")
    @ResponseBody
    public List<Map> queryProductById(Integer id){
        return userService.queryProductById(id);
    }

    /**
     * 查询项目经验
     * @param session
     * @return
     */
    @RequestMapping("queryXiangMu")
    @ResponseBody
    public LayuiPage queryXiangMu(HttpSession session){
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        return userService.queryXiangMu(attribute.getId());
    }

    /**
     * 新增
     * @param jingYanBean
     * @param session
     * @return
     */
    @RequestMapping("addXiangmu")
    @ResponseBody
    public Boolean addXiangmu(JingYanBean jingYanBean,HttpSession session){
        try {
            UserBean attribute = (UserBean) session.getAttribute(session.getId());
            jingYanBean.setUserid(attribute.getId());
            userService.addXiangmu(jingYanBean);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除项目经验
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("delXiangMu")
    public Boolean delXiangMu(Integer id){
        try {
            userService.delXiangMu(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    //投递按钮
    @RequestMapping("addtoudi")
    @ResponseBody
    public void addtoudi(Integer comid,HttpServletRequest request){
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        Integer userid = attribute.getId();

        TouBean touBean = new TouBean();
        touBean.setUserid(userid);
        touBean.setComid(comid);
        userService.addtoudi(comid,userid);
    }

    /**
     * 修改密码
     */
    @RequestMapping("updatePassWord")
    @ResponseBody
    public Map editPassWord(HttpSession session, String password, String pwd1, String pwd2){
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        String passWord2 = attribute.getPassword();
        Integer id = attribute.getId();
        HashMap<String, Object> result = new HashMap<>();
        if(!passWord2.equals(Md5Util.getMd532(password))) {
            result.put("code", 4);
            result.put("msg", "旧密码输入错误");
            return result;
        }
        if (pwd1 == null || pwd1 ==""){
            result.put("code", 1);
            result.put("msg", "密码不能为空");
            return result;
        }
        if(!pwd1.equals(pwd2)) {
            result.put("code", 2);
            result.put("msg", "两次输入的密码不一致，请重新输入");
            return result;
        }
        String md532 = Md5Util.getMd532(pwd1);
        userService.updatePassWord(id,md532);
        result.put("code", 0);
        result.put("msg", "密码修改成功，请从新登录");
        return result;
    }

    //教育经历
    @RequestMapping("findJiaoYu")
    @ResponseBody
    public ResultBean findJiaoYu(HttpSession session){
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        Integer id = attribute.getId();
        return userService.findJiaoYu(id);
    }

    //删除教育经历
    @RequestMapping("delJiaoYu")
    @ResponseBody
    public Boolean delJiaoYu(Integer id){
        try {
            userService.delJiaoYu(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    //新增教育经历
    @RequestMapping("saveJiaoYu")
    @ResponseBody
    public Boolean saveJiaoYu(HttpSession session,JiaoYuBen jiaoYuBen){
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        Integer id = attribute.getId();
        jiaoYuBen.setUserId(id);
        try {
            userService.saveJiaoYu(jiaoYuBen);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     *根据userId 查询具体的数据
     * */
    @RequestMapping("findQueryUserList")
    @ResponseBody
    public UserBean findQueryUserList(Integer id){
        UserBean queryUserList = userService.findQueryUserList(id);
        return queryUserList;
    }
    /**
     *工作经历表
     * */
    @RequestMapping("findUserGongZuoJingLi")
    @ResponseBody
    public ResultBean findUserGongZuoJingLi(HttpSession session){
        System.out.println("工作经历表");
        UserBean userBean = (UserBean) session.getAttribute(session.getId());
        ResultBean userGongZuoJingLi = userService.findUserGongZuoJingLi(userBean.getId());
        return userGongZuoJingLi;
    }
    //删除工作经历
    @RequestMapping("delGongZuo")
    @ResponseBody
    public Boolean delGongZuo(Integer id){
        try {
            userService.delGongZuo(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    //新增工作经历
    @RequestMapping("saveGongZuo")
    @ResponseBody
    public Boolean saveGongZuo(HttpSession session,GongZuoBean gongZuoBean) {
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        Integer id = attribute.getId();
        gongZuoBean.setUserid(id);
        try {
            userService.saveGongZuo(gongZuoBean);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     *技能 特长 查询
     * *//*
    @RequestMapping("findQueryUserJiNengList")
    @ResponseBody
    public ResultBean findQueryUserJiNengList(HttpSession session){
        System.out.println("技能 特长 查询");
        UserBean userBean = (UserBean) session.getAttribute(session.getId());
        ResultBean queryUserJiNengList = userService.findQueryUserJiNengList(userBean.getId());
        return queryUserJiNengList;
    }*/
    /* UserBean userBean = (UserBean) session.getAttribute(session.getId());
        GongZuoBean userGongZuoJingLi = userService.findUserGongZuoJingLi(userBean.getId());
        LayuiPage layuiPage = new LayuiPage();
        layuiPage.setCode(0);
        layuiPage.setCount(1);
        layuiPage.setMsg("查询成功");
        layuiPage.setData(userGongZuoJingLi);*/


    @RequestMapping("queryjituan")
    @ResponseBody
    public List<Map> queryjituan(Integer comid){
        return userService.queryjituan(comid);
    }





}
